package com.fr.ticket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author 付荣
 * @version 创建时间：2019年4月9日 上午10:38:27
 */
public class ProductDetail {

	private static final String prefix_uri = "https://piao.ctrip.com/ticket/dest/t";
	private static final String suffix_uri = ".html";
	private static final int tryTime = 3;

	private static final String prefix_goods_info = "__INITIAL_STATE__ = ";

	public static Set<Long> failList = new HashSet<>();

	public static Map<String, Object> handleProductDetail(long productId, int timeAgin) {

		Map<String, Object> rs = new HashMap<>();
		if (timeAgin > tryTime) {
			failList.add(productId);
			return rs;
		}
		String url = prefix_uri + productId + suffix_uri;
		CloseableHttpResponse response = null;
		int time = 1;
		try {
			HttpGet httpGet = new HttpGet(url);
			response = HttpClientUtil.doRequest(httpGet);
			while (response == null && time < tryTime) {
				response = HttpClientUtil.doRequest(httpGet);
				time++;
			}
			if (response == null) {
				System.out.println("获取详情页失败,url为：" + url);
				return rs;
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream is = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String line = br.readLine();
				while (line != null) {
					int indexOf = line.indexOf(prefix_goods_info, 0);
					if (indexOf > 0) {
						JSONObject object = JSON.parseObject(line.substring(indexOf + prefix_goods_info.length()));
						JSONObject detail = object.getJSONObject("detailInfo");
						JSONObject headerinfo = detail.getJSONObject("headerinfo");
						rs.put("address", headerinfo.getString("addr"));
						JSONObject ressHash = detail.getJSONObject("ressHash");
						for (Object o : ressHash.values()) {
							JSONObject goodsObject = (JSONObject) o;
							GoodsDetail.handleGoodsDetail(productId, goodsObject, 1);
						}
					}
					line = br.readLine();
				}
				br.close();
				is.close();
			}
		} catch (Exception e) {
			System.out.println("详情页" + JSON.toJSONString(e) + productId);
			handleProductDetail(productId, timeAgin + 1);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return rs;
	}

}
